<template>
  <div>
    <el-card>
      <!-- 筛选区域 -->
      <el-row :gutter="20" type="flex" justify="start" align="middle">
        <el-col :span="10">
          <el-input
            placeholder="请输入设备名称"
            v-model="inputValue"
            style="width: 300px; color: #FFFFFF;"
            clearable
            @keyup.enter.native="findDevice"
          ></el-input>
        </el-col>
        <div id="myContainer">
          <el-col :span="5">
            <el-button id="filter-button" type="primary" @click="findDevice">筛选</el-button>
            <el-button id="reset-button" type="default" @click="resetAll">重置</el-button>
            <el-button id="find-button" type="primary" @click="viewDetails">查询</el-button>
          </el-col>
        </div>
      </el-row>
      <!-- 列表区 -->
      <div style="height: 60vh">
        <el-skeleton :loading="loading" animated>
          <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
            <el-table-column type="selection" width="50" align="center">
              <!-- 修改选择列的模板 -->
              <template #default="scope">
                <el-checkbox v-model="scope.row.selected" @change="handleCheckboxChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="deviceName" label="设备名称" />
            <el-table-column prop="counts" label="数量" />
            <el-table-column prop="deviceModel" label="设备型号" />
            <el-table-column prop="deivceNo" label="设备代码" />
            <el-table-column prop="deviceGrade" label="质量等级" />
            <el-table-column prop="manufacture" label="制造厂家" />
          </el-table>
        </el-skeleton>
      </div>
      <!-- 按钮区域 -->
      <el-row style="margin-top: 10px;">
        <el-button style="background-color: #00008B;" @click="selectAll">选择全部</el-button>
        <el-button style="background-color: #00008B;" @click="clearSelection">清除选择</el-button>
        <el-button style="background-color: #00008B;" @click="deleteSelected">删除所选</el-button>
      </el-row>
      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
            :total="total"
            :current-page.sync="searchForm.current"
            :total-pages="totalPages"
            @update:currentPage="handlePageChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import diApi from "@/api/deviceInformation";
import Pagination from "@/components/Table/Pagination";
import { ElMessage } from "element-plus";

const router = useRouter();
// Dom 挂载之后
onMounted(() => {
  getDeviceInformationTableData();
});
// 数据

const inputValue = ref("");
const allTableData = ref([]); // 接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length); // 总记录条数
const totalPages = ref(1); // 总页数
// 监听 allTableData 的变化，并同步更新 tableData
watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
});

const handlePageChange = (page) => {
  searchForm.current = page;
};

// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
});

// 获取诊断结果列表
const getDeviceInformationTableData = async () => {
  // 分页条件查询
  const res = await diApi.getDeviceInfoData();
  if (res.data.status) {
    // 用 all 前缀来接收保存
    console.log(res.data);
    allTableData.value = res.data.data.map(item => ({...item, selected: false }));
  } else {
    ElMessage.error("获取后端数据失败");
    console.log(res.data.message);
  }
};

// 分页监听
// 计算当前页需要显示的数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

const filterData = async () => {
  await getDeviceInformationTableData(searchQuery.value);
};

const resetFilter = () => {
  searchQuery.value = "";
  tableData.value = [...allTableData.value];
  getDeviceInformationTableData();
};

// 加载 loading 页面
const loading = ref(true);
watch(
  () => paginatedData.value,
  (newValue) => {
    loading.value =!(newValue && newValue.length > 0);
  },
  // 配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
  { immediate: true } // 立即执行一次，以确保初始值状态正确
);
onMounted(() => {
  getDeviceInformationTableData();
});

// 添加一个标志，用于标识表格中的每一项是否被选中
const selectedMap = ref({});
tableData.value.forEach((item) => {
  selectedMap.value[item] = item.selected;
});

// 选择全部方法
const selectAll = () => {
  tableData.value.forEach(item => {
    item.selected = true;
  });
};

// 清除选择方法
const clearSelection = () => {
  tableData.value.forEach(item => {
    item.selected = false;
  });
};

// 删除所选方法
const deleteSelected = () => {
  tableData.value.forEach(item => {
    item.selected = false;
  });
};

// 重置所有方法
const resetAll = () => {
  inputValue.value = "";
  getDeviceInformationTableData();
  tableData.value = [...allTableData.value];
  searchForm.current = 1; // 恢复分页到第一页
  selectedMap.value = {};
  tableData.value.forEach((item) => {
    selectedMap.value[item] = false;
  });
};

// 查询设备方法
const findDevice = async () => {
  const queryName = inputValue.value;
  console.log({ deviceName: queryName })
  if (queryName) {
    try {
      const res1 = await diApi.getDeviceNameInfoData({ deviceName: queryName });
      console.log(res1.data);
      if (res1.data.status) {
        allTableData.value = res1.data.data.map(item => ({...item, selected: false }));
        tableData.value = [...allTableData.value];
      } else {
        ElMessage.error("查询设备信息失败");
        console.log(res1.data.message);
      }
    } catch (error) {
      ElMessage.error("与后端通信出现错误");
      console.error(error);
    }
  } else {
    ElMessage.warning("请输入设备名称进行查询");
  }
};

// 处理单个复选框变化的方法
const handleCheckboxChange = row => {
  selectedMap.value[row] = row.selected;
};

// // 查询按钮点击处理方法
// const viewDetails = () => {
//   const selectedDevices = tableData.value.filter(item => item.selected);
//   if (selectedDevices.length > 0) {
//     const deviceNos = selectedDevices.map(device => device.deivceNo);
//     router.push({ name: 'detialInformation', params: { deviceNos } });
//   } else {
//     ElMessage.warning('请选择一个或多个设备进行查询');
//   }
// };

// //可以传输一条数据
// const viewDetails = () => {
//   const selectedDevices = tableData.value.filter(item => item.selected);
//   if (selectedDevices.length > 0) {
//     // 添加检查确保 selectedDevices[0] 存在
//     if (selectedDevices[0]) {
//       const deviceCode = selectedDevices[0].deivceNo;
//       router.push({ name: 'detialInformation', params: { deviceCode } });
//     } else {
//       ElMessage.warning('没有可获取设备代码的选中设备');
//     }
//   } else {
//     ElMessage.warning('请选择一个或多个设备进行查询');
//   }
// };
const viewDetails = () => {
  const selectedDevices = tableData.value.filter(item => item.selected);
  if (selectedDevices.length > 0) {
    const deviceCodes = selectedDevices.map(device => device.deivceNo);
    router.push({ name: 'detialInformation', params: { deviceCodes } });
  } else {
    ElMessage.warning('请选择一个或多个设备进行查询');
  }
};


</script>

<style scoped lang="scss">
#myContainer {
  position: relative;
}
/* 筛选-重置按钮 */
.el-button {
  height: 28px;
  color: #ffffff;
  font-size: 12px;
  border-radius: 3px;
}
#filter-button {
  position: absolute;
  top: 50%;
  left: -150%;
  transform: translate(-50%, -50%);
}
#reset-button {
  background-color: $color-reset-button;
  position: absolute;
  height: 30px;
  color: #ffffff;
  top: 50%;
  left: 200%;
  transform: translate(-50%, -50%);
}
#find-button {
  position: absolute;
  top: 50%;
  left: 3000%;
  width: 100px;
  height: 30px;
  color: #ffffff;
  transform: translate(-50%, -50%);
}
/* card 背景、边框 */
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}
/* 数据表背景 */
:deep(.el-table) {
  color: $color-font-table; // 字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;

  // 鼠标悬停时的行样式
 .el-table__body-wrapper {
   .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}
</style>